import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:provider/provider.dart';
import 'package:myapp/state/bluetooth.dart';
import 'package:myapp/page/blueServices/blueServices.dart';

class Bluetooth extends StatefulWidget {
  const Bluetooth({super.key});

  @override
  State<Bluetooth> createState() => _Content();
}

class _Content extends State<Bluetooth> {
  ///扫描到的蓝牙设备
  late List<ScanResult> _scanResults = [];

  late StreamSubscription<List<ScanResult>> _scanResultsSubscription;
  late StreamSubscription<bool> _isScanningSubscription;

  // 连接状态
  late bool _connectStatus = false;

  // 搜索状态
  bool get isScanning {
    return FlutterBluePlus.isScanningNow;
  }

  @override
  void initState() {
    initBlue();
    super.initState();
  }

  // 打开蓝牙
  Future<void> openBlue() async {
    var subscription =
        FlutterBluePlus.adapterState.listen((BluetoothAdapterState state) {
      if (state == BluetoothAdapterState.on) {
        // 用户已经打开蓝牙
        debugPrint('BluetoothAdapterState-----------');
      } else {
        // 用户还没有打开蓝牙
        debugPrint('error-----------');
      }
    });

    if (Platform.isAndroid) {
      try {
        await FlutterBluePlus.turnOn();
      } catch (err) {
        // 用户拒绝打开蓝牙
        debugPrint('err-----------');
      }
    }
    // 关闭监听
    subscription.cancel();
  }

  // 设置设备监听
  Future<void> setListen() async {
    // 用于监听搜索到的蓝牙设备
    _scanResultsSubscription = FlutterBluePlus.scanResults.listen((results) {
      _scanResults = results;
      if (mounted) {
        setState(() {});
      }
    }, onError: (error) {
      debugPrint('Scan Error:$error');
    });

    // 搜索结束后更新视图
    _isScanningSubscription = FlutterBluePlus.isScanning.listen((state) {
      if (mounted) {
        setState(() {});
      }
    });
  }

  // 扫描设备
  void scanDevices() async {
    try {
      int divisor = Platform.isAndroid ? 8 : 1;
      // 开始搜索蓝牙设备
      await FlutterBluePlus.startScan(
          timeout: const Duration(seconds: 5),
          continuousUpdates: true,
          continuousDivisor: divisor);
    } catch (e) {
      debugPrint("Stop Scan Error:$e");
    }

    if (mounted) {
      setState(() {});
    }
  }

  void stopScan() {
    // 停止搜索
    FlutterBluePlus.stopScan();
  }

  Future<void> initBlue() async {
    await openBlue();
    await setListen();
    scanDevices();
  }

  @override
  void dispose() {
    _scanResultsSubscription.cancel();
    _isScanningSubscription.cancel();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('蓝牙列表',
              style: TextStyle(color: Colors.white, fontSize: 16)),
          toolbarHeight: 40,
          backgroundColor: Colors.deepPurple[300],
          centerTitle: true,
          iconTheme: const IconThemeData(color: Colors.white),
          actions: [
            IconButton(
              icon: const Icon(Icons.settings),
              onPressed: () {
                final bluetoothStore =
                    Provider.of<BluetoothStore>(context, listen: false);
                if (bluetoothStore.device?.servicesList == null) {
                  showAlert('当前没有可用的蓝牙服务，请先连接蓝牙！！！');
                } else {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => const BlueServices()));
                }
              },
            ),
          ],
        ),
        body: Column(
          children: [
            isScanning ? const Text('正在搜索...') : const SizedBox(),
            Expanded(
              child: ListView(
                children: [
                  ..._connectedDevices(),
                  _sectionTitle('扫描到的设备'),
                  ..._buildScanResultTiles(),
                ],
              ),
            ),
          ],
        ),
        floatingActionButton: isScanning
            ? FloatingActionButton(
                backgroundColor: Colors.red,
                onPressed: stopScan,
                child: const Icon(Icons.stop),
              )
            : FloatingActionButton(
                onPressed: scanDevices,
                child: const Icon(Icons.search),
              ));
  }

  void showAlert(String title) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
            title: const Text('提示', style: TextStyle(fontSize: 20)),
            content: Text(title),
            actions: [
              TextButton(
                child: const Text('确定'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              )
            ]);
      },
    );
  }

  Widget _sectionTitle(String title) {
    return Container(
      color: Colors.blue[100],
      margin: const EdgeInsets.all(5.0),
      padding: const EdgeInsets.all(10.0),
      child: Row(
        children: [
          const Icon(Icons.search, size: 24.0, color: Colors.blue), // 左侧图标
          const SizedBox(width: 8.0), // 图标和文本之间的间距
          Text(
            title,
            style: const TextStyle(
              fontSize: 14,
            ),
          ),
        ],
      ),
    );
  }

  List<Widget> _connectedDevices() {
    List<BluetoothDevice> connectedDevices = FlutterBluePlus.connectedDevices;
    if (connectedDevices.isEmpty) {
      return [];
    }
    return [
      _sectionTitle('以绑定的设备'),
      ...connectedDevices.map((device){
        return Container(
          margin: const EdgeInsets.all(5.0),
          padding: const EdgeInsets.all(5.0),
          decoration: BoxDecoration(
            color: Colors.grey[200],
            borderRadius: BorderRadius.circular(8),
          ),
          child: ListTile(
            title: Text(device.platformName,
                style: const TextStyle(fontSize: 14)),
            subtitle: Text(device.remoteId.toString(),
                style: const TextStyle(fontSize: 12)),
            trailing: TextButton(
              onPressed: () async {
                setState(() {
                  _connectStatus = true;
                });
                await context.read<BluetoothStore>().disconnect();
                setState(() {
                  _connectStatus = false;
                });
              },
              child: const Text(
                '断开连接',
                style: TextStyle(color: Colors.deepOrange),
              ),
            )
          ),
        );
      })
    ];

  }

  // 渲染已扫描的蓝牙信息
  List<Widget> _buildScanResultTiles() {
    return _scanResults.map((scanResult) {
      late bool isConnect;
      try {
        isConnect = context.watch<BluetoothStore>().device?.remoteId ==
            scanResult.device.remoteId;
      } catch (err) {
        isConnect = false;
      }
      if (scanResult.device.platformName.isEmpty ||
          scanResult.device.remoteId.toString().toString().isEmpty) {
        return const SizedBox(height: 0);
      } else {
        return Container(
          margin: const EdgeInsets.all(5.0),
          padding: const EdgeInsets.all(5.0),
          decoration: BoxDecoration(
            color: Colors.grey[200],
            borderRadius: BorderRadius.circular(8),
          ),
          child: ListTile(
            title: Text(scanResult.device.platformName,
                style: const TextStyle(fontSize: 14)),
            subtitle: Text(scanResult.device.remoteId.toString(),
                style: const TextStyle(fontSize: 12)),
            trailing: isConnect
                ? TextButton(
                    onPressed: _connectStatus
                        ? null
                        : () async {
                            setState(() {
                              _connectStatus = true;
                            });
                            await context.read<BluetoothStore>().disconnect();
                            setState(() {
                              _connectStatus = false;
                            });
                          },
                    child: const Text(
                      '断开连接',
                      style: TextStyle(color: Colors.deepOrange),
                    ),
                  )
                : TextButton(
                    onPressed: _connectStatus
                        ? null
                        : () async {
                            setState(() {
                              _connectStatus = true;
                            });
                            try {
                              String result = await context
                                  .read<BluetoothStore>()
                                  .connectDevice(scanResult.device);
                              showAlert(result);
                            } catch (e) {
                              showAlert(e as String);
                            }

                            setState(() {
                              _connectStatus = false;
                            });
                          },
                    child: const Text('连接设备'),
                  ),
          ),
        );
      }
    }).toList();
  }
}
